import { login, logout, getUserInfo } from '@/api/user'
import { setToken, getToken } from '@/libs/util'

export default {
  state: {
    username: '',
    c_user_id: '',
    head_img: '',
    token: getToken(),
    num:{
    	act:0,
    	car:0,
    	dot:0,
    	message:0,
    	p_act:0,
    	user:0
    }
  },
  mutations: {
    setAvator (state, head_img) {
      state.head_img = head_img
    },
    setUserId (state, c_user_id) {
      state.c_user_id = c_user_id
    },
    setUserName (state, username) {
      state.username = username
    },
    setAuthToken (state, token) {
      state.token = token
      setToken(token)
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    },
    setNum(state,params){
    	state.num.act =params.act;
    	state.num.car =params.car;
    	state.num.dot =params.dot; 
    	state.num.message =params.message; 
    	state.num.p_act =params.p_act;
    	state.num.user =params.user;
    }
  },
  actions: {
    // 登录
    handleLogin ({ commit }, {username, password}) {
//  	console.log(username);return;
      username = username.trim()
      return new Promise((resolve, reject) => {
        login({
          username,
          password,
          
        }).then(res => {
        	//console.log(res);
          if(res.data.code == 0 ){
          	alert(res.data.msg);
          }else{

					if(res.data.data.pid > 0 ){
						alert('车主无权登录');
						return;
					}
          commit('setAuthToken', res.data.data.auth_token)
          resolve()
          }
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('setAuthToken', '')
//        commit('setAccess', [])
          resolve()
        }).catch(err => {
          reject(err)
        })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // commit('setAccess', [])
        // resolve()
      })
    },
    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo(state.token).then(res => {
            const data = res.data
            commit('setAvator', data.data.car_user.head_img)
            commit('setUserName', data.data.car_user.username)
            commit('setUserId', data.data.car_user.c_user_id)
//          commit('setAccess', data.access)
            commit('setHasGetInfo', true)
            commit('setNum',{
            	act:data.data.num.act,
				    	car:data.data.num.car,
				    	dot:data.data.num.dot,
				    	message:data.data.num.message,
				    	p_act:data.data.num.p_act,
				    	user:data.data.num.user
            })
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    }
  }
}
